"""
工位管理路由
"""
from datetime import datetime
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query

from models.schemas import (
    User,
    Workstation,
    WorkstationConfig,
    RealtimeStatus,
    WorkstationSearchResponse,
    WorkstationSearchItem,
    WorkstationListResponse,
    SyncWorkstationRequest,
    WorkstationActionRequest,
    WorkstationActionResponse,
    ActionResult,
    UploadActionsRequest,
    UploadActionsResponse,
    ActionHistoryResponse,
    ActionHistory
)
from auth.dependencies import get_current_user
from utils.response import success_response, error_response


router = APIRouter(prefix="/workstations", tags=["工位管理"])


# 模拟本地工位数据
MOCK_LOCAL_WORKSTATIONS = {
    1: {
        "id": 1,
        "name": "工位A-001",
        "status": "idle",
        "config": {
            "location": "车间A-1层",
            "devices": ["机械臂", "传感器", "PLC"],
            "parameters": {
                "speed": 100,
                "precision": 0.01
            }
        },
        "realtime_status": {
            "cpu_usage": 45,
            "memory_usage": 62,
            "task_progress": 78,
            "running_time": "2小时15分",
            "completed_tasks": 156,
            "error_count": 3
        },
        "created_at": "2025-10-01T08:00:00",
        "updated_at": "2025-10-05T10:30:00"
    },
    2: {
        "id": 2,
        "name": "工位B-002",
        "status": "running",
        "config": {
            "location": "车间A-2层",
            "devices": ["机械臂", "视觉系统", "PLC"]
        },
        "created_at": "2025-10-01T08:00:00",
        "updated_at": "2025-10-05T10:30:00"
    },
    3: {
        "id": 3,
        "name": "工位C-003",
        "status": "error",
        "config": {
            "location": "车间B-1层",
            "devices": ["机械臂", "传感器"]
        },
        "created_at": "2025-10-02T09:00:00",
        "updated_at": "2025-10-05T11:00:00"
    }
}

# 模拟云端可搜索的工位
MOCK_CLOUD_WORKSTATIONS = [
    {"name": "工位A-001", "description": "车间A-1层装配工位", "published_at": "2025-10-01T08:00:00"},
    {"name": "工位A-002", "description": "车间A-1层检测工位", "published_at": "2025-10-02T09:00:00"},
    {"name": "工位A-003", "description": "车间A-2层装配工位", "published_at": "2025-10-03T10:00:00"},
    {"name": "工位B-001", "description": "车间B-1层装配工位", "published_at": "2025-10-01T08:00:00"},
    {"name": "工位B-002", "description": "车间B-2层检测工位", "published_at": "2025-10-02T09:00:00"},
    {"name": "工位C-001", "description": "车间C-1层装配工位", "published_at": "2025-10-01T08:00:00"},
    {"name": "工位D-004", "description": "车间D-1层测试工位", "published_at": "2025-10-04T10:00:00"},
]

# 模拟操作历史
MOCK_ACTION_HISTORY = [
    {
        "id": 1,
        "action": "start",
        "status": "success",
        "message": "工位启动成功",
        "executed_at": "2025-10-04T10:30:25",
        "executed_by": "admin"
    },
    {
        "id": 2,
        "action": "config_update",
        "status": "success",
        "message": "配置更新完成",
        "executed_at": "2025-10-04T09:15:10",
        "executed_by": "admin"
    },
    {
        "id": 3,
        "action": "init",
        "status": "success",
        "message": "系统初始化",
        "executed_at": "2025-10-04T08:00:00",
        "executed_by": "system"
    }
]


@router.get("/search", summary="模糊搜索工位名称")
async def search_workstations(
    keyword: str = Query(..., description="搜索关键词，支持模糊匹配"),
    limit: int = Query(10, ge=1, le=50, description="返回数量限制，默认10，最大50"),
    current_user: User = Depends(get_current_user)
):
    """
    模糊搜索已发布的工位名称，用于同步工位时选择
    
    此接口用于搜索云端已发布的工位配置，返回的是可同步的工位名称列表
    
    需要认证：是
    """
    # 模糊搜索
    results = [
        ws for ws in MOCK_CLOUD_WORKSTATIONS
        if keyword.lower() in ws["name"].lower() or keyword.lower() in ws["description"].lower()
    ]
    
    # 限制返回数量
    results = results[:limit]
    
    response_data = WorkstationSearchResponse(
        total=len(results),
        items=[WorkstationSearchItem(**item) for item in results]
    )
    
    return success_response(data=response_data.model_dump())


@router.get("", summary="获取本地工位列表")
async def get_workstations(
    status: Optional[str] = Query(None, description="工位状态筛选: idle/running/error/offline"),
    current_user: User = Depends(get_current_user)
):
    """
    获取本地已同步的工位信息列表
    
    需要认证：是
    """
    workstations = list(MOCK_LOCAL_WORKSTATIONS.values())
    
    # 状态筛选
    if status:
        workstations = [ws for ws in workstations if ws["status"] == status]
    
    response_data = WorkstationListResponse(
        total=len(workstations),
        items=[Workstation(**ws) for ws in workstations]
    )
    
    return success_response(data=response_data.model_dump())


@router.get("/{id}", summary="获取工位详情")
async def get_workstation_detail(
    id: int,
    current_user: User = Depends(get_current_user)
):
    """
    根据工位ID获取工位详细信息
    
    需要认证：是
    """
    workstation = MOCK_LOCAL_WORKSTATIONS.get(id)
    
    if not workstation:
        return error_response(404, "工位不存在")
    
    return success_response(data=Workstation(**workstation).model_dump())


@router.post("/sync", summary="同步工位信息")
async def sync_workstation(
    request: SyncWorkstationRequest,
    current_user: User = Depends(get_current_user)
):
    """
    通过工位名称从云端同步工位配置信息
    
    需要认证：是
    """
    # 检查工位名称是否存在于云端
    cloud_workstation = next(
        (ws for ws in MOCK_CLOUD_WORKSTATIONS if ws["name"] == request.name),
        None
    )
    
    if not cloud_workstation:
        return error_response(400, f"云端不存在名为 '{request.name}' 的工位")
    
    # 检查是否已同步
    existing = next(
        (ws for ws in MOCK_LOCAL_WORKSTATIONS.values() if ws["name"] == request.name),
        None
    )
    
    if existing:
        return error_response(400, f"工位 '{request.name}' 已经同步过了")
    
    # 创建新工位（模拟）
    new_id = max(MOCK_LOCAL_WORKSTATIONS.keys()) + 1
    now = datetime.now().isoformat()
    
    new_workstation = {
        "id": new_id,
        "name": request.name,
        "status": "idle",
        "config": {
            "location": cloud_workstation["description"],
            "devices": ["待配置"]
        },
        "created_at": now,
        "updated_at": now
    }
    
    MOCK_LOCAL_WORKSTATIONS[new_id] = new_workstation
    
    return success_response(
        data=Workstation(**new_workstation).model_dump(),
        message="工位同步成功"
    )


@router.post("/{id}/action", summary="执行工位操作")
async def execute_workstation_action(
    id: int,
    request: WorkstationActionRequest,
    current_user: User = Depends(get_current_user)
):
    """
    对指定工位执行控制操作（启动/暂停/停止/复位）
    
    需要认证：是
    """
    workstation = MOCK_LOCAL_WORKSTATIONS.get(id)
    
    if not workstation:
        return error_response(404, "工位不存在")
    
    # 检查当前状态是否允许执行此操作（简化版）
    current_status = workstation["status"]
    action = request.action
    
    # 状态转换规则（简化）
    allowed_actions = {
        "idle": ["start", "reset"],
        "running": ["pause", "stop"],
        "error": ["reset", "stop"],
        "offline": ["reset"]
    }
    
    if action not in allowed_actions.get(current_status, []):
        return error_response(
            400,
            "工位当前状态不允许执行此操作",
            data={
                "current_status": current_status,
                "allowed_actions": allowed_actions.get(current_status, [])
            }
        )
    
    # 执行操作（模拟）
    action_id = f"act_{int(datetime.now().timestamp() * 1000)}"
    now = datetime.now().isoformat()
    
    # 更新工位状态
    status_map = {
        "start": "running",
        "pause": "idle",
        "stop": "idle",
        "reset": "idle"
    }
    workstation["status"] = status_map.get(action, current_status)
    workstation["updated_at"] = now
    
    response_data = WorkstationActionResponse(
        action_id=action_id,
        workstation_id=id,
        action=action,
        status="success",
        executed_at=now,
        result=ActionResult(
            message=f"工位{action}操作成功",
            details=request.parameters
        )
    )
    
    return success_response(
        data=response_data.model_dump(),
        message="操作执行成功"
    )


@router.post("/{id}/actions", summary="上传工位操作历史")
async def upload_action_history(
    id: int,
    request: UploadActionsRequest,
    current_user: User = Depends(get_current_user)
):
    """
    上传工位操作历史记录到服务器
    
    需要认证：是
    """
    workstation = MOCK_LOCAL_WORKSTATIONS.get(id)
    
    if not workstation:
        return error_response(404, "工位不存在")
    
    # 模拟上传（实际应该存储到数据库）
    uploaded_count = len(request.actions)
    failed_count = 0
    
    response_data = UploadActionsResponse(
        uploaded_count=uploaded_count,
        failed_count=failed_count
    )
    
    return success_response(
        data=response_data.model_dump(),
        message="操作历史上传成功"
    )


@router.get("/{id}/actions", summary="获取工位操作历史")
async def get_action_history(
    id: int,
    start_time: Optional[str] = Query(None, description="开始时间，ISO 8601格式"),
    end_time: Optional[str] = Query(None, description="结束时间，ISO 8601格式"),
    page: int = Query(1, ge=1, description="页码，默认1"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量，默认20"),
    current_user: User = Depends(get_current_user)
):
    """
    获取指定工位的操作历史记录
    
    需要认证：是
    """
    workstation = MOCK_LOCAL_WORKSTATIONS.get(id)
    
    if not workstation:
        return error_response(404, "工位不存在")
    
    # 返回模拟数据
    response_data = ActionHistoryResponse(
        total=len(MOCK_ACTION_HISTORY),
        items=[ActionHistory(**item) for item in MOCK_ACTION_HISTORY]
    )
    
    return success_response(data=response_data.model_dump())
